<template>
  <div class="login">
    <!-- 头部 -->
    <van-nav-bar title="会员登录" left-arrow @click-left="$router.go(-1)"/>
    <!-- 主体 -->
    <div class="container">
      <div class="title">
        <h1>手机号验证</h1>
        <p>未注册手机号登录后将自动注册</p>
      </div>
      <div class="form">
        <div class="form-item">
          <input v-model="moblie" class="inp" type="text" maxlength="11" placeholder="请输入手机号">
        </div>
        <div class="form-item">
          <input v-model="picCode" class="inp"  type="text" maxlength="5" placeholder="请输入图形验证码">
          <img v-if="picUrl" :src="picUrl" alt="" @click="getPicCode">
        </div>
        <div class="form-item">
          <input v-model="msgCode" class="inp" type="text"  placeholder="请输入短信验证码">
          <button @click="getCode">{{second===totalSecond?'获取验证码': second+'秒后重新发送'}}</button>
        </div>
      </div>
      <div class="login-btn" @click="login">登录</div>
    </div>
  </div>
</template>

<script>

import { getPicCode, getMsgCode, codeLogin } from '@/api/login'
// import { Toast } from 'vant'
export default {
  name: 'LoginIndex',
  data () {
    return {
      picCode: '', // 用户输入的图形验证码
      picKey: '', // 将来请求图形验证码的唯一标识
      picUrl: '', // 存储请求渲染的图形地址
      totalSecond: 60, // 总秒数
      second: 60, // 当前秒数，开定时器对 second--
      timer: null, // 定时器id
      moblie: '', // 手机号
      msgCode: '' // 短信验证码
    }
  },
  created () {
    this.getPicCode()
  },
  methods: {
    async getPicCode () {
      const { data: { base64, key } } = await getPicCode()
      this.picUrl = base64
      this.picKey = key
      this.$toast.success('获取图形验证码成功！')
    },
    // 校验手机号 验证码是否合法
    validFn () {
      if (!/^1[3-9]\d{9}$/.test(this.moblie)) {
        this.$toast('请输入正确的手机号')
        return false
      }
      if (!/^\w{4}$/.test(this.picCode)) {
        this.$toast('请输入正确的验证码')
        return false
      }
      return true
    },

    // 获取验证码
    async getCode () {
      if (!this.validFn()) {
        // 手机号 、图形验证码校验后才能往下走
        return
      }
      // 当前没有定时开着，且totalSecond和second 一致（秒数归位）才可以开启倒计时
      if (!this.timer && this.second === this.totalSecond) {
        // 响应的status非200 最抛出一个promise await只会等待成功的promise
        const res = await getMsgCode(this.picCode, this.picKey, this.moblie)
        console.log(res)

        // 响应拦截器实现错误处理
        // if (!(res.status >= 200 && res.status <= 300)) {
        //   this.$toast('验证码错误！')
        //   this.getPicCode()
        //   this.picCode = ''
        //   return
        // }
        this.$toast('短信发送成功，请注意查收')
        // 开启定时器
        this.timer = setInterval(() => {
          this.second--
          // 判断second值>=0
          if (this.second <= 0) {
            clearInterval(this.timer)
            this.timer = null // 重置定时器id
            this.second = this.totalSecond // 恢复秒数
          }
        }, 1000)
      }
    },
    // 登录
    async login () {
      if (!this.validFn()) {
        return
      }
      if (!/^\d{6}$/.test(this.msgCode)) {
        this.$toast('请输入正确的短信验证码')
        return
      }
      const res = await codeLogin(this.msgCode, this.moblie)
      console.log(res)
      this.$store.commit('user/setUserInfo', res.data)
      this.$toast('登陆成功')
      // 判断地址栏是否回调地址
      // 有则=> 回跳
      // 无责=>正常跳转即可
      const url = this.$route.query.backUrl || '/'
      this.$router.replace(url)
    }

  },
  // 离开页面清除定时器
  destroyed () {
    clearInterval(this.timer)
  }
}
</script>

<style lang="less" scoped>
.container{
  padding: 49px 29px;

  .title{
    margin-bottom: 20px;
    h3{
      font-size: 26px;
      font-weight: normal;
    }
    p{
      line-height: 40px;
      font-size: 14px;
      color: #b8b8b8;
    }
  }
  .form-item{
    border-bottom: 1px solid #f3f1f2;
    padding: 8px;
    margin-bottom: 14px;
    display: flex;
    align-items: center;
    .inp{
      display: block;
      border: 8px;
      outline: none;
      height: 32px;
      font-size: 14px;
      flex: 1;
    }
    img{
      width: 94px;
      height: 31px;
    }
    button{
      height: 31px;
      border: none;
      font-size: 13px;
      color: #cea26a;
      background-color: transparent;
      padding-right: 9px;
    }
  }
  .login-btn{
    width: 100%;
    height: 42px;
    margin-top: 39px;
    background: linear-gradient(90deg,#ecb53c,#ff9211);
    color: #fff;
    border-radius: 39px;
    box-shadow: 0 10px 20px 0 rgba(0, 0, 0, .1);
    letter-spacing: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
